// 引入颜色模型命名空间
using RestfulApi.Models;

// 定义数据访问层命名空间
namespace RestfulApi.Data
{
    // 颜色仓储类，负责颜色数据的CRUD操作
    public class ColorRepository
    {
        // 静态颜色列表，模拟数据库存储
        private static List<Color> _colors = new List<Color>
        {
            // 初始化三个颜色示例
            new Color { 
                Id = 1, 
                Name = "红色", 
                HexCode = "#FF0000", 
                RgbValue = new RgbValue { Red = 255, Green = 0, Blue = 0 },
                Category = new ColorCategory { Id = 1, Name = "暖色", Description = "暖色系列" },
                Metadata = new ColorMetadata {
                    CreatedAt = DateTime.Now.AddMonths(-6),
                    CreatedBy = "系统管理员",
                    Usage = new ColorUsage {
                        UsageCount = 120,
                        Applications = new List<string> { "网页设计", "平面设计", "室内装饰" },
                        Industry = new ColorIndustry {
                            IndustryName = "设计行业",
                            Popularity = 0.85,
                            Details = new ColorIndustryDetails {
                                Year = 2023,
                                Season = "春季",
                                HistoricalData = new List<ColorHistoricalData> {
                                    new ColorHistoricalData { Year = 2021, MarketShare = 0.75, Trend = "上升" },
                                    new ColorHistoricalData { Year = 2022, MarketShare = 0.80, Trend = "上升" }
                                }
                            }
                        }
                    },
                    Trend = new ColorTrend {
                        CurrentTrend = "热门",
                        GrowthRate = 0.15,
                        Forecast = new ColorForecast {
                            NextYear = 2024,
                            PredictedPopularity = 0.90,
                            MarketAnalysis = new ColorMarketAnalysis {
                                EmergingMarkets = new List<string> { "移动应用", "网页设计" },
                                DecliningMarkets = new List<string> { "印刷媒体" },
                                CompetitorAnalysis = new ColorCompetitorAnalysis {
                                    MainCompetitors = new List<string> { "橙色", "粉色" },
                                    StrategicAdvice = "保持在品牌识别中的应用"
                                }
                            }
                        }
                    }
                }
            },
            new Color { 
                Id = 2, 
                Name = "绿色", 
                HexCode = "#00FF00", 
                RgbValue = new RgbValue { Red = 0, Green = 255, Blue = 0 },
                Category = new ColorCategory { Id = 2, Name = "冷色", Description = "冷色系列" },
                Metadata = new ColorMetadata {
                    CreatedAt = DateTime.Now.AddMonths(-4),
                    CreatedBy = "色彩专家",
                    Usage = new ColorUsage {
                        UsageCount = 95,
                        Applications = new List<string> { "环保产品", "健康行业", "自然主题" },
                        Industry = new ColorIndustry {
                            IndustryName = "环保行业",
                            Popularity = 0.78,
                            Details = new ColorIndustryDetails {
                                Year = 2023,
                                Season = "夏季",
                                HistoricalData = new List<ColorHistoricalData> {
                                    new ColorHistoricalData { Year = 2021, MarketShare = 0.65, Trend = "稳定" },
                                    new ColorHistoricalData { Year = 2022, MarketShare = 0.72, Trend = "上升" }
                                }
                            }
                        }
                    },
                    Trend = new ColorTrend {
                        CurrentTrend = "稳定增长",
                        GrowthRate = 0.08,
                        Forecast = new ColorForecast {
                            NextYear = 2024,
                            PredictedPopularity = 0.82,
                            MarketAnalysis = new ColorMarketAnalysis {
                                EmergingMarkets = new List<string> { "可持续产品", "有机食品" },
                                DecliningMarkets = new List<string> { "传统包装" },
                                CompetitorAnalysis = new ColorCompetitorAnalysis {
                                    MainCompetitors = new List<string> { "青色", "蓝绿色" },
                                    StrategicAdvice = "强调环保和可持续发展理念"
                                }
                            }
                        }
                    }
                }
            },
            new Color { 
                Id = 3, 
                Name = "蓝色", 
                HexCode = "#0000FF", 
                RgbValue = new RgbValue { Red = 0, Green = 0, Blue = 255 },
                Category = new ColorCategory { Id = 2, Name = "冷色", Description = "冷色系列" },
                Metadata = new ColorMetadata {
                    CreatedAt = DateTime.Now.AddMonths(-2),
                    CreatedBy = "UI设计师",
                    Usage = new ColorUsage {
                        UsageCount = 150,
                        Applications = new List<string> { "企业网站", "社交媒体", "科技产品" },
                        Industry = new ColorIndustry {
                            IndustryName = "科技行业",
                            Popularity = 0.92,
                            Details = new ColorIndustryDetails {
                                Year = 2023,
                                Season = "全年",
                                HistoricalData = new List<ColorHistoricalData> {
                                    new ColorHistoricalData { Year = 2021, MarketShare = 0.85, Trend = "上升" },
                                    new ColorHistoricalData { Year = 2022, MarketShare = 0.90, Trend = "上升" }
                                }
                            }
                        }
                    },
                    Trend = new ColorTrend {
                        CurrentTrend = "非常热门",
                        GrowthRate = 0.12,
                        Forecast = new ColorForecast {
                            NextYear = 2024,
                            PredictedPopularity = 0.95,
                            MarketAnalysis = new ColorMarketAnalysis {
                                EmergingMarkets = new List<string> { "人工智能", "云服务" },
                                DecliningMarkets = new List<string> { "传统零售" },
                                CompetitorAnalysis = new ColorCompetitorAnalysis {
                                    MainCompetitors = new List<string> { "深蓝色", "紫色" },
                                    StrategicAdvice = "在科技和创新领域保持领先地位"
                                }
                            }
                        }
                    }
                }
            }
        };

        // 获取所有颜色的方法
        public IEnumerable<Color> GetAll()
        {
            // 返回所有颜色列表
            return _colors;
        }

        // 根据过滤条件获取颜色
        public IEnumerable<Color> GetFiltered(ColorFilter filter)
        {
            var query = _colors.AsQueryable();

            if (!string.IsNullOrEmpty(filter.Name))
            {
                query = query.Where(c => c.Name.Contains(filter.Name));
            }

            if (!string.IsNullOrEmpty(filter.CategoryName))
            {
                query = query.Where(c => c.Category.Name.Contains(filter.CategoryName));
            }

            if (filter.IsDarkColor.HasValue)
            {
                if (filter.IsDarkColor.Value)
                {
                    // 简单判断深色：R+G+B < 384 (平均值128的3倍)
                    query = query.Where(c => c.RgbValue.Red + c.RgbValue.Green + c.RgbValue.Blue < 384);
                }
                else
                {
                    query = query.Where(c => c.RgbValue.Red + c.RgbValue.Green + c.RgbValue.Blue >= 384);
                }
            }

            return query.ToList();
        }

        // 根据ID获取单个颜色的方法
        public Color? GetById(int id)
        {
            // 使用LINQ查询匹配ID的颜色，如果不存在则返回null
            return _colors.FirstOrDefault(c => c.Id == id);
        }

        // 添加新颜色的方法
        public Color Add(Color color)
        {
            // 获取当前最大ID值
            var maxId = _colors.Count > 0 ? _colors.Max(c => c.Id) : 0;
            // 为新颜色分配ID（最大ID+1）
            color.Id = maxId + 1;
            // 将新颜色添加到列表中
            _colors.Add(color);
            // 返回添加后的颜色（包含新ID）
            return color;
        }

        // 批量添加颜色
        public IEnumerable<Color> AddBatch(IEnumerable<Color> colors)
        {
            var result = new List<Color>();
            foreach (var color in colors)
            {
                result.Add(Add(color));
            }
            return result;
        }

        // 更新现有颜色的方法
        public bool Update(Color color)
        {
            // 查找要更新的颜色索引
            var index = _colors.FindIndex(c => c.Id == color.Id);
            // 如果颜色不存在，返回失败
            if (index == -1)
                return false;

            // 更新颜色信息
            _colors[index] = color;
            // 返回成功标志
            return true;
        }

        // 删除颜色的方法
        public bool Delete(int id)
        {
            // 查找要删除的颜色
            var color = GetById(id);
            // 如果颜色不存在，返回失败
            if (color == null)
                return false;

            // 从列表中移除颜色
            _colors.Remove(color);
            // 返回成功标志
            return true;
        }
    }
}